
//
//  HDUserAccoutViewModel.swift
//  HDSwfitWeibo
//
//  Created by wty on 16/4/11.
//  Copyright © 2016年 wty. All rights reserved.
//

import UIKit

class HDUserAccoutViewModel: NSObject {

    //创建单例
    static  let  userAccoutShare :HDUserAccoutViewModel = HDUserAccoutViewModel()
    
    //创建HDUserAccoutViewModel()  单例后调用这个方法
    private  override init() {
        super.init()
        //加载账号
        userAccount = loadUserAcccount()
    }
    
    //创建模型属性
    var userAccount:HDUserAccount?
    
    //定义一个计算属性  来判断用户是否登录
    var userLogin : Bool {
        return  userAccount != nil
    }
    //MARK -实现加载accessToken
    func loadAccessToken ( code : String , callBack:(error:NSError?)->()) {
        //1.url
        let urlString = accessTokenURLString
        let parameters =  [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": grant_type,
            "code": code,
            "redirect_uri": redirect_uri
        ]
        //3.发送请求

        HDNetWorkTools.shareNetwork.POST(urlString, parameters: parameters, progress: nil, success: { (task, responseObject) -> Void in
            //获取数据
            let result = responseObject as? [String: AnyObject]

            //字典转模型 用户可选绑定
            if let dict = result {
                self.userAccount = HDUserAccount(dict: dict)
                //保存数据
                self.saveUserAccount()
                //将数据用闭包形式传递出去
                callBack(error: nil)
            }
            }) { ( task, error) -> Void in
                //如果失败就传递失败信息
                callBack(error: error)
        }
    }
    
    //MARK -首页数据网络请求
   func loadHomeInfo(callBack:(error:NSError?)->()) {
        //请求参数从模型中获取用守卫判断一下
        guard let access_token = userAccount?.access_token else {
            //绑定失败
            //自定义错误信息
            let error  =  HDNetworkErrorEnum.AccessTokenEmpty.error()
            callBack(error: error)
            return
        }
        
        guard let uid = userAccount?.uid else {
            let error = HDNetworkErrorEnum.UidEmpty.error()
            callBack(error: error)
            return
        }
        
        //请求url
        let urlString = "https://api.weibo.com/2/users/show.json"
        //请求参数
        let parameters = [
            "access_token": access_token,
            "uid": uid
        ]
        //发送请求参数回调
        HDNetWorkTools.shareNetwork.GET(urlString, parameters: parameters, progress: nil, success: { (task, responseObject) -> Void in
             //字典装模型
            if let dict = responseObject as? [String:AnyObject]{
            self.userAccount?.screen_name = dict["screen_name"] as? String
            self.userAccount?.avatar_large = dict["avatar_large"] as? String
            }
            //保存数据
            self.saveUserAccount()
            //回调空
                callBack(error : nil)
            }) { (task, error) -> Void in
                //回调失败
                callBack(error: error)
        }
    }

    //MARK -  归档和解档数据
    //保存账号  就是归档
    private func saveUserAccount() {
        if let userAccount = userAccount {
            NSKeyedArchiver.archiveRootObject(userAccount, toFile: accountPath)
            
        }
    }
    
    //解档从沙盒中加载数据
    func loadUserAcccount ()->HDUserAccount?{
        //解档账号  是一个可选属性
        let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath ) as? HDUserAccount
        //可选绑定 判断账号是否有值    判断账号是否过期
        if let account = userAccount where account.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            // TODO
            return account
        }
        return nil
    }
}
